package com.ruoyi.web.controller.rest.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.web.service.DictService;
import com.ruoyi.system.domain.WebMallUserOrder;
import com.ruoyi.system.domain.WebMallUserOrderProduct;
import com.ruoyi.system.domain.WebUser;
import com.ruoyi.system.service.*;
import com.ruoyi.system.vo.WebMallUserOrderSaveVO;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wsliupan
 * @title: _MallProductController
 * @projectName yuansheng
 * @description: 商城订单信息
 * @date 2021-6-1422:10
 */
//@Api(tags = "商城订单")
//@RestController
//@RequestMapping("/rest/user/mall")
public class _UserMallController extends BaseController{
    @Autowired
    private IWebMallProductService iWebMallProductService;
    @Autowired
    private ISysConfigService iSysConfigService;
    @Autowired
    private IWebUserService iWebUserService;
    @Autowired
    private IWebMallUserOrderService iWebMallUserOrderService;

    @ApiOperation(value = "商城订单列表",notes = "数量改成销量")
    @GetMapping()
    @ApiResponses({
            @ApiResponse(code = 200, message = "返回成功",response = WebMallUserOrder.class),
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true),
            @ApiImplicitParam(name = "status", value = "状态，订单状态1待付款2待发货4交易关闭 6待收货 100完成", required = true)
    })
    public AjaxResult list(Integer userId,Integer status) {
        WebUser userData = iWebUserService.getById(userId);
        if (userData == null) {
            return error(Constants.REQUIRED_FAILD);
        }
//        IPage<WebMallUserOrder> ipage = new Page<WebMallUserOrder>(1, 10);
//        IPage<WebMallUserOrder> data = iWebMallUserOrderService.page(ipage,new QueryWrapper<WebMallUserOrder>()
//                .eq("user_id","Y")
//                .orderByDesc("create_time"));
        List<WebMallUserOrder> data = iWebMallUserOrderService.list(new QueryWrapper<WebMallUserOrder>()
                .eq("user_id",userId)
                .eq("order_status",status)
                .orderByDesc("create_time"));
        return AjaxResult.success(data);
    }

    @ApiOperation(value = "计算订单金额")
    @GetMapping("calc")
    public AjaxResult calc(WebMallUserOrderSaveVO orderSaveVO){
        WebUser userData = iWebUserService.getById(orderSaveVO.getUserId());
        if (userData == null) {
            return error(Constants.REQUIRED_FAILD);
        }
        List<Map<String,Object>> productMaps = new ArrayList<>();
        BigDecimal orderMoney = iWebMallUserOrderService.getOrderMoney(orderSaveVO , productMaps);
        BigDecimal payMoney = orderMoney;
        if(orderSaveVO.getUseScore() !=null && 1 == orderSaveVO.getUseScore()){
            payMoney = iWebMallUserOrderService.useScorePayMoney(userData.getScore(),orderMoney);
        }
        Map map = new HashMap();
        map.put("payMoney",payMoney);
        return AjaxResult.success(map);
    }

    @ApiOperation(value = "确认订单",notes = "skuTitle:属性标题，skuValue:属性值，scoreCount：用户积分>0可以选择使用积分，" +
            "productName:产品名称，targetMoney：单价，orderTotal：订单总金额，payMoney：待支付金额")
    @PostMapping("preSave")
    public AjaxResult preSave(WebMallUserOrderSaveVO orderSaveVO){
        WebUser userData = iWebUserService.getById(orderSaveVO.getUserId());
        if (userData == null) {
            return error(Constants.REQUIRED_FAILD);
        }
        List<Map<String,Object>> productMaps = new ArrayList<>();
        BigDecimal orderMoney = iWebMallUserOrderService.getOrderMoney(orderSaveVO , productMaps);
        BigDecimal payMoney = orderMoney;
        if(orderSaveVO.getUseScore() !=null && 1== orderSaveVO.getUseScore()){
            payMoney = iWebMallUserOrderService.useScorePayMoney(userData.getScore(),orderMoney);
        }

        Map<String,Object> mapData = new HashMap<>();
        mapData.put("scoreCount",userData.getScore());
        mapData.put("orderTotal",orderMoney);
        mapData.put("payMoney",payMoney);
        mapData.put("products",productMaps);

        return AjaxResult.success(mapData);
    }

    @ApiOperation(value = "保存下单")
    @PostMapping("save")
    public AjaxResult save(WebMallUserOrderSaveVO orderSaveVO){
        Map<String, Object> map = iWebMallUserOrderService.saveOrder(orderSaveVO);
        return AjaxResult.success(map);
    }

    @ApiOperation(value = "取消订单")
    @PostMapping("calcel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true),
            @ApiImplicitParam(name = "orderId", value = "订单id"),
    })
    public AjaxResult cancel(Integer userId , Integer orderId){
        WebUser userData = iWebUserService.getById(userId);
        if (userData == null) {
            return error(Constants.REQUIRED_FAILD);
        }
        WebMallUserOrder order =  iWebMallUserOrderService.getById(orderId);
        if(order == null || order.getUserId().intValue() != userId.intValue()){
            return error(Constants.REQUIRED_FAILD);
        }
        iWebMallUserOrderService.cancelOrder(orderId);
        return AjaxResult.success();
    }

    @ApiOperation(value = "订单详情")
    @GetMapping("detail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true),
            @ApiImplicitParam(name = "orderId", value = "订单id"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功-订单字段",response = WebMallUserOrder.class),
            @ApiResponse(code = 201, message = "成功-订单商品字段",response = WebMallUserOrderProduct.class),
    })
    public AjaxResult detail(Integer userId , Integer orderId){
        WebUser userData = iWebUserService.getById(userId);
        if (userData == null) {
            return error(Constants.REQUIRED_FAILD);
        }
        WebMallUserOrder order =  iWebMallUserOrderService.getById(orderId);
        if(order == null || order.getUserId().intValue() != userId.intValue()){
            return error(Constants.REQUIRED_FAILD);
        }

        //查询订单状态
        String orderStatus = dictService.getLabel("mall_order_status",order.getOrderStatus()+"");

        List<WebMallUserOrderProduct> listProduct = iWebMallUserOrderProductService.list(new QueryWrapper<WebMallUserOrderProduct>()
                .eq("order_id",order.getId()));

        Map<String,Object> map = new HashMap<>();
        map.put("order",order);
        map.put("listProduct",listProduct);
        map.put("orderStatus_",orderStatus);
        return AjaxResult.success(map);
    }

    @Autowired
    private IWebMallUserOrderProductService iWebMallUserOrderProductService;
    @Autowired
    private DictService dictService;
}
